var app = new Vue({
    el: '#app',
    data: {
        word: null,
        guess: null,
        score: 0,
        lives: 1,
        chinese: '',
        level: 0,
        over: false,
        message: '',
        btn_msg: '',
        win: false,
        btns: null,
    },
    methods: {
        btn_style: function (index) {
            visible = 'visible';
            if (!this.btns[index]) {
                visible = 'hidden';
            }
            return {
                margin: '10px',
                height: '40px',
                width: '40px',
                visibility: visible
            };
        },
        click_btn: function (index, event) {
            if (app.over) {
                return;
            }
            this.btns[index] = '';
            key = event.target.innerText;
            var bingo = false;
            for(var i = 0; i < this.word.length; i++) {
                if (this.word[i].toUpperCase() == key && !this.guess[i]) {
                    Vue.set(this.guess, i, key);
                    bingo = true;
                    break;
                }
            }
            if (!bingo) {
                this.lives --;
            }
            if (this.lives <= 0) {
                this.message = '失败了！答案是 ' + this.word;
                this.btn_msg = '返回'
                this.over = true;
                this.win = false;
            }
            if (this.guess.join('') == this.word) {
                this.message = ' 正确！';
                this.btn_msg = '下一题'
                this.over = true;
                this.win = true;
            }
        },
        finish: function (event) {
            if (app.over) {
                if (app.win) {
                    $.ajax({
                        url: '/guess/game/finish/',
                        data: {level:app.level, lives:app.lives},
                        success: init
                    });

                } else {
                    $.ajax({
                        url: '/guess/game/finish/',
                        data: {level:app.level, lives:0},
                        success:function(data){
                            window.location.href = '/guess/user/profile/?finish=1';
                        }
                    });
                }
            }
        }
    }
})

function init(data){
    app.score = data.score;
    app.lives = data.lives;
    app.word = data.word;
    app.chinese = data.chinese;
    app.level = data.level
    app.guess = Array(app.word.length);
    app.over = false;
    app.btns = data.choices
}

created: {
    $.ajax({
        url: '/guess/game/level/',
        dataType: 'json',
        success: init
    });
}

